package sys.knot.integration.util;

import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.controller.client.OperationBuilder;
import org.jboss.as.controller.client.helpers.ClientConstants;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.junit.Before;

import javax.inject.Inject;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;

/**
 * Base class for arquillian tests.
 * - Creates 2 deployments, the knot-server.war and a dummy for running tests from "the outside".
 * - Adds 2 datasources: db1 & db3.
 * - Fills datasources with 30 dummy rows in a dummy table, see @DatabaseFiller
 */
public class ArquillianBase {

    @Inject
    DatabaseFiller databaseFiller;

    @Deployment(order = 1, name = "main_app", testable = false)
    public static WebArchive createMainAppDeployment() {
        addDataSource("db1");
        addDataSource("db3");

        File[] libs = Maven.resolver().loadPomFromFile("pom.xml").importRuntimeAndTestDependencies().asFile();

        File warFile = new File("../knot-server/target/knot-server.war");
        WebArchive war = ShrinkWrap.createFromZipFile(WebArchive.class, warFile);

        return war;
    }

    @Deployment(order = 2)
    public static WebArchive createTestRunningDeployment() {
        File[] libs = Maven.resolver().loadPomFromFile("pom.xml").importRuntimeAndTestDependencies().asFile();

        WebArchive war = ShrinkWrap.create(WebArchive.class, "testrunner.war");
        for(File file : libs){
            war.addAsLibrary(file);
        }
        war.addPackages(true, "sys.knot");

        war.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");

        return war;
    }

    private static void addDataSource(String name) {
        ModelNode request = new ModelNode();
        request.get(ClientConstants.OP).set(ClientConstants.ADD);
        request.get(ClientConstants.OP_ADDR).add("subsystem", "datasources");
        request.get(ClientConstants.OP_ADDR).add("data-source", name);
        request.get("jndi-name").set("java:jboss/datasources/" + name);
        request.get("connection-url").set("jdbc:h2:mem:" + name + ";DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");
        request.get("driver-name").set("h2");
        try {
            ModelControllerClient client = ModelControllerClient.Factory.create(InetAddress.getByName("127.0.0.1"), 19990);
            client.execute(new OperationBuilder(request).build());
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Before
    public void addDummyData() {
        databaseFiller.ensureDummyData();
    }
}
